﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace FSD_2_Content_Editor
{
    
    public partial class Form1 : Form
    {
        string xmlLocation;

        public struct GameItem
        {
            public int GameType;
            public string TitleID;
            public string Executable;
            public int Discnr;
            public int Favourite;
            public string Path;
        };

        int count = 0;

        public string test1;
        public int test2, progressValue = 0;

        delegate void progressStatus(int proStat);
        GameItem[] GameArray = new GameItem[2000];

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FavouritecomboBox.SelectedIndex = 0;
            titleIDlabel.Text = "";
            Pathlabel.Text = "";
            Executablelabel.Text = "";
            FavouritecomboBox.Enabled = false;
            ContentTypecomboBox.Enabled = false;
            Savebutton.Enabled = false;
            this.Text = "FSD2 Content Editor " + this.ProductVersion.ToString().Remove(5, 2);

            
        }

        private void Openbutton_Click(object sender, EventArgs e)
        {
            //Open fsd2content.xml
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    
                    xmlLocation = openFileDialog1.FileName;
                    StreamReader XMLDoc = new StreamReader(xmlLocation);
                    
                    string xmlstring;
                    xmlstring = XMLDoc.ReadToEnd().Replace("&", "&amp;");//.Replace("'", "&apos");
                    File.WriteAllText("tempXML.xml", xmlstring, Encoding.UTF8);

                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load("tempXML.xml");
                    ItemlistBox.Items.Clear();

                    ContentTypecomboBox.SelectedIndex = -1;
                    FavouritecomboBox.SelectedIndex = -1;
                    count = 0;
                    XmlNodeList Game = xDoc.GetElementsByTagName("game");
                    
                    for (int i = 0; i < Game.Count; i++)
                    {
                        GameArray[i].GameType = Convert.ToInt16(Game.Item(i).Attributes.Item(0).InnerText);
                        GameArray[i].TitleID = Game.Item(i).Attributes.Item(1).InnerText;
                        GameArray[i].Executable = Game.Item(i).Attributes.Item(2).InnerText;
                        GameArray[i].Discnr = Convert.ToInt16(Game.Item(i).Attributes.Item(3).InnerText);
                        GameArray[i].Favourite = Convert.ToInt16(Game.Item(i).Attributes.Item(4).InnerText);
                        GameArray[i].Path = Game.Item(i).InnerText;
                        count++;
                    }
                    XMLDoc.Close();

                    for (int i = 0; i < count; i++)
                    {
                        ItemlistBox.Items.Add(GameArray[i].Path);
                    }

                    ContentTypecomboBox.Enabled = true;
                    FavouritecomboBox.Enabled = true;
                    Savebutton.Enabled = true;
                    Statuslabel.Text = "Parsing Names";
                    GameNamebackgroundWorker.WorkerReportsProgress = true;
                    GameNamebackgroundWorker.RunWorkerAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void ItemlistBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                int i = ItemlistBox.SelectedIndex;
                if (GameArray[i].GameType != -1)
                {
                    ContentTypecomboBox.SelectedIndex = GameArray[i].GameType;
                   
                }
                else
                {
                    ContentTypecomboBox.SelectedIndex = 5;
                }
                
                titleIDlabel.Text = GameArray[i].TitleID;
                Executablelabel.Text = GameArray[i].Executable;
                Pathlabel.Text = GameArray[i].Path.Replace("&", "&&");
                FavouritecomboBox.SelectedIndex = GameArray[i].Favourite;
                DiscNumbercomboBox.SelectedIndex = GameArray[i].Discnr;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GameNamebackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (File.Exists("GameDataBase.xml"))
                {
                    GameNamebackgroundWorker.WorkerReportsProgress = true;
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load("GameDataBase.xml");

                    XmlNodeList Game = xDoc.GetElementsByTagName("Game");
                    //XmlNodeList TitleIDxml = xDoc.GetElementsByTagName("TitleID");
                    //XmlNodeList GameNamexml = xDoc.GetElementsByTagName("GameName");
                    int Count = Game.Count - 1;
                    Setprogmax(count);
                    SetprogVal(0);
                    int GamesCount = 0;

                    for (int i = 0; i < count; i++)
                    {
                        bool Found = false;
                        for (int index = 0; index <= Count; index++)
                        {

                            string tempTitleID = GameArray[i].TitleID.ToUpper();
                            string blah = Game.Item(index).ChildNodes.Item(1).InnerText.ToUpper();
                            if (tempTitleID.CompareTo(blah) == 0)  //(TitleID == blah) ;//Game.Item(index).ChildNodes.Item(0).InnerText.ToUpper()) ; //TitleIDxml.Item(index).InnerText.ToUpper());
                            {

                                GamesCount++;
                                test2 = GamesCount;
                                test1 = Game.Item(index).ChildNodes.Item(0).InnerText.ToString().Replace("&", "&&");
                                Found = true;
                                //this.GamesListView.Items[GamesCount].SubItems[0].Text = Game.Item(index).ChildNodes.Item(0).InnerText.ToString(); //GameNamexml.Item(index).ChildNodes.Item(index).InnerText;
                                break;
                                //GameNamebackgroundWorker.ReportProgress(+1);
                            }
                        }
                        if (Found == true)
                        {
                            GameNamebackgroundWorker.ReportProgress(i);
                            System.Threading.Thread.Sleep(30);
                        }
                        else
                        {
                            SetprogVal(progressValue += 1);
                            test1 = "";
                            test2 = 0;
                            //test
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void GameNamebackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Statuslabel.Text = "Idle";
            progressBar1.Maximum = 100;
            progressBar1.Value = 100;
        }

        private void GameNamebackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (test1 != "")
            {
                ItemlistBox.Items[e.ProgressPercentage] = test1;
            }
            SetprogVal(progressValue += 1);
        }

        public void Setprogmax(int Prog)
        {
            if (this.progressBar1.InvokeRequired)
            {
                progressStatus d = new progressStatus(Setprogmax);
                this.Invoke(d, new object[] { Prog });
            }
            else
            {
                this.progressBar1.Maximum = Prog;
                

            }

        }
        public void SetprogVal(int Val)
        {
            if (this.progressBar1.InvokeRequired)
            {
                progressStatus d = new progressStatus(SetprogVal);
                this.Invoke(d, new object[] { Val });
            }
            else
            {
                this.progressBar1.Value = Val;
                this.progressBar1.Refresh();
                progressValue = progressBar1.Value;
            }

        }

        private void FavouritecomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ItemlistBox.SelectedIndex != -1)
            {
                if (GameArray[ItemlistBox.SelectedIndex].TitleID != null)
                {
                    GameArray[ItemlistBox.SelectedIndex].Favourite = FavouritecomboBox.SelectedIndex;
                }
            }
        }

        private void ContentTypecomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ItemlistBox.SelectedIndex != -1)
            {
                if (GameArray[ItemlistBox.SelectedIndex].TitleID != null)
                {
                    if (ContentTypecomboBox.SelectedIndex != 5)
                    {
                        GameArray[ItemlistBox.SelectedIndex].GameType = ContentTypecomboBox.SelectedIndex;
                    }
                    else
                    {
                        GameArray[ItemlistBox.SelectedIndex].GameType = -1;
                    }
                }
            }
        }

        private void Savebutton_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string saveLocation = saveFileDialog1.FileName;

                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Indent = true;
                    settings.Encoding = Encoding.UTF8;
                    settings.NewLineOnAttributes = false;
                    settings.CheckCharacters = false;
                    
                    XmlWriter xmlWr = XmlWriter.Create(saveLocation, settings);
                    
                    xmlWr.WriteStartDocument();
                    xmlWr.WriteStartElement("freestyle");

                    for (int i = 0; i < ItemlistBox.Items.Count; i++)
                    {
                        xmlWr.WriteStartElement("game");
                        xmlWr.WriteStartAttribute("type");
                        xmlWr.WriteValue(GameArray[i].GameType);
                        xmlWr.WriteEndAttribute();
                        xmlWr.WriteStartAttribute("id");
                        xmlWr.WriteValue(GameArray[i].TitleID);
                        xmlWr.WriteEndAttribute();
                        xmlWr.WriteStartAttribute("executable");
                        xmlWr.WriteValue(GameArray[i].Executable);
                        xmlWr.WriteEndAttribute();
                        xmlWr.WriteStartAttribute("discnr");
                        xmlWr.WriteValue(GameArray[i].Discnr);
                        xmlWr.WriteEndAttribute();
                        xmlWr.WriteStartAttribute("favorite");
                        xmlWr.WriteValue(GameArray[i].Favourite);
                        xmlWr.WriteEndAttribute();
                        xmlWr.WriteString(GameArray[i].Path);
                        //if(GameArray[i].Path == "usb0:\\games\\Prey\\")
                        xmlWr.WriteEndElement();
                    }
                    xmlWr.WriteEndElement();
                    xmlWr.WriteEndDocument();
                    xmlWr.Close();

                    //StreamReader rd = new StreamReader(saveLocation);// File.OpenRead(saveLocation.ToString());

                    //string textWr = rd.ReadToEnd().Replace("&amp;", "&");
                    //rd.Close();
                    //File.WriteAllText(saveLocation, textWr, Encoding.UTF8);
                    

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void DiscNumbercomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            GameArray[ItemlistBox.SelectedIndex].Discnr = DiscNumbercomboBox.SelectedIndex;
        }
    }
}
